// pages/gaokao/gk_exam_registrationInfo/gk_exam_registrationInfo.js
const http = require('../../../utils/http.js');
const tools = require('../../../utils/tools.js');

Page({
  data: {
    // 1. 基础信息（保持不变）
    base_candidate_info: {
      id_number: '',
      phone: '',
      name: '',
      gender: '',
      birth_date: '',
      ethnicity_id: '',
      foreign_language_id: '',
      political_status_id: ''
    },
    // 2. 学籍基础信息（改为 gk_academic_info）
    gk_academic_info: {
      city_code: '',
      county_code: '',
      registration_point_code: '',
      graduate_type_id: '',
      graduate_school_code: '',
      graduate_school_name: '',
      graduate_class: '',
      study_school_code: '',
      study_school_name: '',
      study_class: '',
      registration_authority: '',
      registered_residence_code: '',
      registered_residence_name: '',
      household_immigration: 0,
      household_immigration_date: '',
      migrant_children: 0
    },
    // 3. 报考信息（改为 gk_exam_info）
    gk_exam_info: {
      exam_type: '',
      apply_type: '',
      candidate_type_code: '',
      foreign_language_test_id: 0,
      promise_junior_college: 0,
      national_special: 0,
      university_special: 0,
      local_special: 0,
      free_medical_orientation: 0,
      mailing_address: '',
      postal_code: '',
      recipient_name: '',
      recipient_phone: ''
    },

    expanded: {
      base: false,
      academic: false,
      exam: false
    },

    // 映射容器
    idToName: {
      ethnicity: {},
      political: {},
      writtenLang: {},
      graduateType: {},
      examType: {},
      applyType: {},
      candidateType: {},
      oralLang: {},
      residence: {},
      authority: {},
      city: {},
      county: {},
      registrationPoint: {},
      foreignLanguageTest: {}
    },
  },

  formatDate(ds) {
    if (!ds) return '';
    const d = new Date(ds);
    return `${d.getFullYear()}-${(d.getMonth()+1).toString().padStart(2,'0')}-${d.getDate().toString().padStart(2,'0')}`;
  },

  async onLoad() {
    // 从本地读取
    const b = wx.getStorageSync('base_candidate_info')  || {};
    let a = wx.getStorageSync('gk_academic_info')   || {};
    let e = wx.getStorageSync('gk_exam_info')       || {};

    if(JSON.stringify(a) === '{}'){
      await tools.loadExamInfo(b.id_number)
      a = wx.getStorageSync('gk_academic_info')   || {};
      e = wx.getStorageSync('gk_exam_info')       || {};
    }

    if (b.birth_date) b.birth_date = this.formatDate(b.birth_date);
    if (a.household_immigration_date) a.household_immigration_date = this.formatDate(a.household_immigration_date);

    this.setData({
      base_candidate_info: b,
      gk_academic_info: a,
      gk_exam_info: e
    });

    await this.fetchNameMappings();
  },

  fetchNameMappings() {
    // 定义要映射的字段及详情接口
    const mapCfg = [
      { key: 'ethnicity',    field: 'ethnicity_id',        url: id => `/ethnicity/info?id=${id}` },
      { key: 'political',    field: 'political_status_id', url: id => `/politicalstatus/info?id=${id}` },
      { key: 'writtenLang',  field: 'foreign_language_id',  url: id => `/foreignlanguage/info?id=${id}` },
      { key: 'oralLang',     field: 'foreign_language_test_id', url: id => `/foreignlanguage/info?id=${id}` },
      { key: 'graduateType', field: 'graduate_type_id',    url: id => `/gaokao/GkGraduateType/${id}` },
      { key: 'examType',     field: 'exam_type',            url: code => `/gaokao/ExamType/${code}` },
      { key: 'applyType',    field: 'apply_type',           url: code => `/gaokao/ApplyType/${code}` },
      { key: 'candidateType',field: 'candidate_type_code',  url: code => `/gaokao/CandidateType/${code}` },
      { key: 'residence',    field: 'registered_residence_code', url: code => `/gaokao/GkRegisteredResidence/${code}` },
      { key: 'authority',    field: 'registration_authority',    url: code => `/gaokao/GkRegistrationAuthority/${code}` },
      { key: 'county', field: 'county_code',  url: code => `/gaokao/GkCounty/${code}` },
      { key: 'city', field: 'city_code',  url: code => `/city/info?id=${code}` },
      { key: 'registrationPoint', field: 'registration_point_code',  url: code => `/gaokao/GkCounty/${code}` },
    ];

    const { base_candidate_info: B, gk_academic_info: A, gk_exam_info: E } = this.data;
    const promises = [];

    mapCfg.forEach(({ key, field, url }) => {
      const val = B[field] || A[field] || E[field];
      if (!val) return;
      promises.push(
        http.get(url(val)).then(res => {
          if(key === "city" && res.statusCode === 200 && res.data){
            this.setData({ [`idToName.${key}.${val}`]: res.data.cityName });
          }
          else if (res.statusCode === 200 && res.data.data) {
            this.setData({ [`idToName.${key}.${val}`]: res.data.data.name });
          }
        })
      );
    });
    return Promise.all(promises).catch(console.error);
  },

  toggleSection(e) {
    const s = e.currentTarget.dataset.section;
    this.setData({ [`expanded.${s}`]: !this.data.expanded[s] });
  },

  navigateToEdit(e) {
    const sec = e.currentTarget.dataset.section;
    // 学籍->2，报考->3
    wx.navigateTo({
      url: `/pages/chengkao/chengkao_page${sec}/chengkao_page${sec}`
    });
  }
});
